#include "gpio_device.h"
#include "gpio.h"
#include "my_errno.h"
#include <string.h>

static int GPIOInit(struct GPIO_Device *ptDev)
{
	if (NULL == ptDev)
		return -EINVAL;

	return ESUCCESS;
}

static int GPIOWrite(struct GPIO_Device *ptDev, int status)
{
	if (NULL == ptDev)
		return -EINVAL;

	PGPIOData ptGPIOData = ptDev->privData;
	GPIO_PinState state = status ? GPIO_PIN_RESET : GPIO_PIN_SET;
	HAL_GPIO_WritePin(ptGPIOData->port, ptGPIOData->pin, state);

	return ESUCCESS;
}

static int GPIORead(struct GPIO_Device *ptDev)
{
	if (NULL == ptDev)
		return -EINVAL;

	PGPIOData ptGPIOData = ptDev->privData;
	return HAL_GPIO_ReadPin(ptGPIOData->port, ptGPIOData->pin);
//	ptGPIOData->value = HAL_GPIO_ReadPin(ptGPIOData->port, ptGPIOData->pin);

//	return ESUCCESS;
}

static int GPIOKeyScan(struct GPIO_Device *ptDev)
{
	if (NULL == ptDev)
		return -EINVAL;

	PGPIOData ptGPIOData = ptDev->privData;
	ptGPIOData->keyBuf = ptGPIOData->keyBuf << 1 | ptDev->Read(ptDev);
	if (ptGPIOData->keyBuf == 0x00)
		ptDev->value = 0;
	else if (ptGPIOData->keyBuf == 0xFF)
		ptDev->value = 1;

	return ESUCCESS;
}


//---------------------------------------------
//----------output
static GPIOData g_tLEDBlueData = { LED_BLUE_GPIO_Port, LED_BLUE_Pin};
static GPIODevice g_tLEDBlue = {
	"led_blue",
	1,
	GPIOInit,
	GPIOWrite,
	GPIORead,
	NULL,
	&g_tLEDBlueData
};

static GPIOData g_tLEDWhiteData = { LED_WHITE_GPIO_Port, LED_WHITE_Pin};
static GPIODevice g_tLEDWhite = {
	"led_white",
	1,
	GPIOInit,
	GPIOWrite,
	GPIORead,
	NULL,
	&g_tLEDWhiteData
};

static GPIOData g_tLEDGreenData = { LED_GREEN_GPIO_Port, LED_GREEN_Pin};
static GPIODevice g_tLEDGreen = {
	"led_green",
	1,
	GPIOInit,
	GPIOWrite,
	GPIORead,
	NULL,
	&g_tLEDGreenData
};

//----------input
static GPIOData g_tKey1Data = { KEY1_GPIO_Port, KEY1_Pin, 0xFF};
static GPIODevice g_tKey1 = {
	"key1",
	1,
	GPIOInit,
	GPIOWrite,
	GPIORead,
	GPIOKeyScan,
	&g_tKey1Data
};

static GPIOData g_tKey2Data = { KEY2_GPIO_Port, KEY2_Pin, 0xFF};
static GPIODevice g_tKey2 = {
	"key2",
	1,
	GPIOInit,
	GPIOWrite,
	GPIORead,
	GPIOKeyScan,
	&g_tKey2Data
};


static PGPIODevice g_ptGPIODevices[] = {
	&g_tLEDBlue, &g_tLEDGreen, &g_tLEDWhite,
	&g_tKey1, &g_tKey2
};

//---------------------------------------------
PGPIODevice GetGPIODevice(char *name)
{
	for (int i = 0; i < sizeof(g_ptGPIODevices)/sizeof(g_ptGPIODevices[0]); i++)
	{
		if (!strcmp(g_ptGPIODevices[i]->name, name))
			return g_ptGPIODevices[i];
	}

	return NULL;
}



